sub guess_type
{
    for (shift)
    {
	return "nfs" if /:/;
	chomp(my $fstyp = `fstyp 2>/dev/null`);
	return $fstyp || "ext3";
    }
}

my $nfs = 0;
my $reload = 0;

if (my $mounts = fetchall_hash("mounts"))
{
    while (my ($path, $info) = each %{ $mounts })
    {
	$info = { device => $info } unless ref $info;

	my $device = $info->{device} || "none";
	my $type = $info->{type} || guess_type($device) || "ignore";
	my $opts = $info->{options} || "defaults";
	my $freq = $info->{dump_freq} || 0;
	my $passno = $info->{passno} || 0;

	$opts .= ",noatime,nodiratime"
	    if $type =~ /^ext[23]$/ and not fetch_val('preserve_atime') and $opts !~ /\bnoatime\b/;

	my $line = sprintf "%-23s %-23s %-7s %-15s %-1s %-1s\n", $device, $path, $type, $opts, $freq, $passno;

	dir_check $path, -quiet => 1;
	file_append '/etc/fstab', $line, qr/^\S+\s+\Q$path\E\s/
	    and $reload++;

	$nfs = 1 if $type eq 'nfs';
    }
}

foreach my $mount (fetch_all('nfs_mount'))
{
    foreach my $host (sort keys %{ $mount })
    {
	while (my ($export, $info) = each %{ $mount->{$host} })
	{
	    $info = { path => $info } unless ref $info;

	    my $path = $info->{path};
	    my $device = "$host:$export";
	    my $type = "nfs";
	    my $opts = $info->{options} || "defaults";
	    my $freq = $info->{dump_freq} || 0;
	    my $passno = $info->{passno} || 0;

	    my $line = sprintf "%-23s %-23s %-7s %-15s %-1s %-1s\n", $device, $path, $type, $opts, $freq, $passno;

	    dir_check $path, -quiet => 1;
	    file_append '/etc/fstab', $line, qr/^\S+\s+\Q$path\E\s/
		and $reload++;
	}
    }

    $nfs = 1;
}

# enable noatime and nodiratime by default
unless (fetch_val('preserve_atime'))
{
    file_modify '/etc/fstab', -eval => sub {
	my ($device, $path, $type, $opts, $freq, $passno) = split " ", $_;
	return unless $type =~ /^ext[23]$/;
	my $changed = 0;
	$opts =~ /\b\Q$_\E\b/ or $opts .= ",$_", $changed++
	    foreach qw(noatime nodiratime); 
	return unless $changed;
	$_ = sprintf "%-23s %-23s %-7s %-15s %-1s %-1s\n", $device, $path, $type, $opts, $freq, $passno;
	queue_command 'mount', '-oremount,noatime,nodiratime', $path;
    };
}

add_class "NFS_$hostname" => {
    services => {
	portmap => 1,
	nfslock => 1,
    },
} if $nfs;

queue_command "mount -a"
    if $reload;

1;
